package org.ltt.rbac.config;

import org.ltt.rbac.config.provider.PhoneAuthenticationProvider;
import org.ltt.rbac.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.*;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.ArrayList;
import java.util.List;

/**
 * 认证管理 配置
 *  多种方式认证
 *
 */
@Configuration
public class WebSecurityConfig {

    @Autowired
    private PhoneAuthenticationProvider phoneAuthenticationProvider;

    @Autowired
    private UserService userServiceImpl;


    /**
     * 加密算法
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder(10);
    }

    /**
     * 认证方式 -- 用户密码认证方式
     * @return
     */
    @Bean
    public DaoAuthenticationProvider daoAuthenticationProvider(){
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
        daoAuthenticationProvider.setUserDetailsService(userServiceImpl);
        return daoAuthenticationProvider;
    }
    /**
     * 认证管理器
     * @return
     */
    @Bean
    public AuthenticationManager authenticationManager(){
        List<AuthenticationProvider> providers = new ArrayList<>();
        // 添加认证方式
        providers.add(daoAuthenticationProvider());//默认的用户密码认证方式
        providers.add(phoneAuthenticationProvider);// 添加 手机验证码认证方式

        // 将 认证方式 添加到管理器中
        ProviderManager providerManager = new ProviderManager(providers);
        // 设置 认证事件发布器
        //providerManager.setAuthenticationEventPublisher(new DefaultAuthenticationEventPublisher(applicationEventPublisher));
        return providerManager;
    }

    /**
     * 认证事件发布器
     * @param applicationEventPublisher
     * @return
     */
    @Bean
    public AuthenticationEventPublisher authenticationEventPublisher(ApplicationEventPublisher applicationEventPublisher){
        return new DefaultAuthenticationEventPublisher(applicationEventPublisher);
    }


}
